package com.itheima.aspect;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;


/*
    记录日志的切面类
*/
@Slf4j
@Component
@Aspect //切面类
public class LogAspect {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;


    /**
     * @return Object
     * @description 环绕通知：哪个方法上使用@Log注解就对哪个方法增强
     * 需求：获取日志信息，调用OperateLogMapper方法保存日志信息到表中
     * @param[1] pjp
     */
    @Around("@annotation(com.itheima.aspect.Log)")
    @SneakyThrows
    //在参数列表输入pjp，是固定的
    public Object recordLog(ProceedingJoinPoint pjp) {
        //    1. private Integer operateUser; //操作人ID
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parserJwt(jwt);//解析jwt，得到载荷部分
        Integer operateUser = (Integer) claims.get("id");

        //    2. private LocalDateTime operateTime; //操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //    3. private String className; //操作类名
        String className = pjp.getTarget().getClass().getName();

        //    4. private String methodName; //操作方法名
        String methodName = pjp.getSignature().getName();

        //    5. private String methodParams; //操作方法参数，保存json数据
        Object[] args = pjp.getArgs();
        String methodParams = objectMapper.writeValueAsString(args);

        long start = System.currentTimeMillis();
        //    6. private String returnValue; //操作方法返回值，保存json数据
        //执行目标对象方法，调用原始目标方法运行
        Object result = pjp.proceed();
        String returnValue = objectMapper.writeValueAsString(result);

        //    7. private Long costTime; //操作耗时
        long end = System.currentTimeMillis();
        long costTime = end - start;


        //将上述结果封装成OperateLog对象，调用OperateLogMapper方法添加到日志表中
        OperateLog operateLog = new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime);
        operateLogMapper.insert(operateLog);

        log.info("AOP记录操作日志: {}" , operateLog);

        return result;//返回到客户端
    }

}